import {Component, AfterViewInit, ViewChild, OnInit} from '@angular/core';
import { TopMenu, ImageSlider, ImageSliderComponent } from './shared/components';
import {AuthKey} from '@configs/constant';
import {UserService} from '@services/user.service';
import {AccountService} from '@services/account.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, AfterViewInit {
  menus: TopMenu[] = [
    { title: '热门', link: '/hot' },
    { title: '男装', link: '/man' },
    { title: '女装', link: '/women' },
    { title: '卫衣', link: '/shirt' },
    { title: '运动鞋', link: '/sheet' },
    { title: '毛衣', link: '/hot' },
    { title: 'T恤', link: '/hot' },
    { title: '帽子', link: '/cap' },
    { title: '墨镜', link: '/hot' },
    { title: '夹克', link: '/hot' },
    { title: '衬衫', link: '/hot' }
  ];
  imageSliders: ImageSlider[] = [
    {
      id: 1,
      imgUrl: 'http://p1.music.126.net/taavXOqTkSZsxG7OYoJeuQ==/109951170467350162.jpg',
      link: '#',
      caption: ''
    },
    {
      id: 2,
      imgUrl: 'http://p1.music.126.net/UblpFfOdSc4XMc6xMRacgQ==/109951170467314601.jpg',
      link: '#',
      caption: ''
    },
    {
      id: 3,
      imgUrl: 'http://p1.music.126.net/BTBxjNbbiTi8MESdC8CtYg==/109951170467330612.jpg',
      link: '#',
      caption: ''
    },
    {
      id: 4,
      imgUrl: 'http://p1.music.126.net/qW_1VfogVX6AzItVBeka9w==/109951170467337689.jpg',
      link: '#',
      caption: ''
    },
    {
      id: 5,
      imgUrl: 'http://p1.music.126.net/vFWg2elMOjI6da7oF-LZTA==/109951170467440440.jpg',
      link: '#',
      caption: ''
    }
  ];
  @ViewChild(ImageSliderComponent, { static: true }) imgSlider: ImageSliderComponent;
  constructor(
    private userServe: UserService,
    private accountServe: AccountService
  ) {}
  ngOnInit() {
    this.refreshUser();
  }
  ngAfterViewInit() {
    console.log('App-AfterViewInit-imgSlider:', this.imgSlider);
  }
  private refreshUser(): void {
    this.userServe.user$.subscribe(currentUser => {
      const authKey = window.localStorage.getItem(AuthKey);
      if (!currentUser && authKey) {
        this.accountServe.account().subscribe(({user, token}) => {
          window.localStorage.setItem(AuthKey, token);
          this.userServe.setUser(user);
        });
      }
    });
  }
}
